package ycl.base.common;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import ycl.base.common.enums.ApiResultEnum;

import java.io.Serializable;

/**
 * 统一返回对象
 *
 * @author: YCL
 * @date: 2021-06-06 09:19:45
 */
@Data
public class ApiResult<T> implements Serializable {

	private static final long serialVersionUID = 2047317951422915349L;

	private T data;

	@ApiModelProperty(value = "状态:200.成功  500.失败  2.未登录  3.没有权限  4.密码错误 -1.未知异常，请联系管理员")
	private String code;

	private boolean isSuccess;

	@ApiModelProperty(value = "消息内容")
	private String msg;


	public ApiResult() {
	}

	//成功返回 --------------------

	public static <T> ApiResult<T> success() {
		return ApiResult.success(null, null);
	}

	public static <T> ApiResult<T> success(T data) {
		return ApiResult.success(data, "操作成功");
	}

	public static <T> ApiResult<T> success(T data, String message) {
		ApiResult<T> apiResult = new ApiResult<>();
		apiResult.setSuccess(true);
		apiResult.setData(data);
		apiResult.setCode(ApiResultEnum.SUCCESS.code);
		apiResult.setMsg(message);
		return apiResult;
	}


	//失败返回 --------------------

	public static ApiResult<Object> fail(String msg) {
		return fail(ApiResultEnum.ERROR.code, msg, null);
	}

	public static <T> ApiResult<T> fail(String code, String message, T data) {
		ApiResult<T> apiResult = new ApiResult<>();
		apiResult.setCode(code);
		apiResult.setData(data);
		apiResult.setMsg(message);
		return apiResult;
	}

	public static <T> ApiResult<T> error(String code, String message) {
		ApiResult<T> apiResult = new ApiResult<>();
		apiResult.setCode(code);
		apiResult.setMsg(message);
		return apiResult;
	}

	public static <T> ApiResult<T> defaultError(Class<T> clazz) {
		ApiResult<T> apiResult = new ApiResult<>();
		apiResult.setCode(ApiResultEnum.ERROR.code);
		apiResult.setMsg("服务器异常");
		return apiResult;
	}

	public static <T> ApiResult<T> badRequest(String msg) {
		ApiResult<T> apiResult = new ApiResult<>();
		apiResult.setCode("400");
		apiResult.setData(null);
		apiResult.setMsg(msg);
		return apiResult;
	}


	@Override
	public String toString() {
		return JSON.toJSONString(this);
	}
}
